package work.chenxr.websocket.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import work.chenxr.websocket.service.WebSocketService;

/**
 * @Author Chenxr
 * @Date 2023/10/21
 * @Description WebSocket控制器
 */
@Controller
@AllArgsConstructor
public class WebSocketController {
    private final WebSocketService webSocketService;

    @GetMapping
    public String index() {
        return "index.html";
    }

    /**
     * 此方法未在前端页面中使用，请自行调用
     */
    @PostMapping("/push")
    public ResponseEntity<?> pushToWeb(@RequestBody String content) {
        JSONObject data = JSON.parseObject(content);
        webSocketService.sendMsg(data.getString("toUserId"), data.getString("content"));
        return ResponseEntity.ok("success");
    }
}
